#lang racket

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence)))))

(define (enumerate-interval low high)
  (if (> low high)
      '()
      (cons low (enumerate-interval (+ low 1) high))))

(define (flatmap proc seq)
  (accumulate append '() (map proc seq)))

(define (sum seq)
  (if (null? seq)
      0
      (+ (car seq) (sum (cdr seq)))))


(define (n-triple-sum-s n s)
  (filter (lambda (triple) (= s (sum triple)))
          (flatmap
           (lambda (i) (map (lambda (j) (append i (list j)))
                            (enumerate-interval 1 n)))
           (flatmap (lambda (i) (map (lambda (j) (list j i))
                                     (enumerate-interval 1 n)))
                    (enumerate-interval 1 n)))))

(n-triple-sum-s 3 8)

